﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;


namespace AMing.Api.Data
{
    public class SqlHelper
    {
        private string GetConnenctionString()
        {
            SqlConnectionStringBuilder sqlConentStr = new SqlConnectionStringBuilder();
            sqlConentStr.DataSource = Config.DB_IP;
            sqlConentStr.InitialCatalog = Config.DB_Name;
            sqlConentStr.UserID = Config.DB_UserName;
            sqlConentStr.Password = Config.DB_Password;

            return sqlConentStr.ConnectionString;
        }

        private SqlConnection GetConnenction()
        {
            SqlConnection connent = new SqlConnection(GetConnenctionString());

            return connent;
        }

        public List<Model.KeyValue> Read(string sql, params SqlParameter[] sqlpar)
        {
            var connent = GetConnenction();
            List<Model.KeyValue> list = new List<Model.KeyValue>();
            try
            {
                connent.Open();
                SqlCommand com = new SqlCommand(sql, connent);

                if (sqlpar.Length > 0)
                    com.Parameters.AddRange(sqlpar);

                var ready = com.ExecuteReader();

                while (ready.Read())
                {
                    Model.KeyValue kv = new Model.KeyValue
                    {
                        Key = ready["key"].ToString(),
                        Value = ready["value"].ToString()
                    };
                    list.Add(kv);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                connent.Close();
            }

            return list;
        }


        public int Execute(string sql, params SqlParameter[] sqlpar)
        {
            var connent = GetConnenction();
            try
            {
                connent.Open();
                SqlCommand com = new SqlCommand(sql, connent);

                if (sqlpar.Length > 0)
                    com.Parameters.AddRange(sqlpar);

                return com.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                connent.Close();
            }

            return -1;
        }
    }
}
